
if (typeof downloadcontrol === undefined) {
    downloadcontrol = {};
}

$(document).ready(function() {
    
    var ns = downloadcontrol;
    
    ns._invalidTimeout = null;
    
    ns.processDownloadRequest = function(data, status) {
        if (!data['success']) {
            alert("Could not get a download URL, reason: " + data['msg']);
            return false;
        }
        var url_parts = data['url'].split('?')[0].split("/");
        var basename = url_parts[ url_parts.length-1 ];
        // replace underscores and dashes so that the link spans multiple lines
        basename = basename.replace(/[_-]/g, ' ');
        var link = '<a href="'+data['url']+'">Download '+basename+'</a>';
        $("#download_press_kit #download_url").html(link);
        clearTimeout(ns._invalidTimeout);
        var timeout = (data['expires_in']-5)*1000; // 5 min padded just a bit in case the Amazon clock beats us
        ns._invalidTimeout = setTimeout(function() {
            $("#download_press_kit #download_url").html('<span class="error">This link has expired.</span>');
        }, timeout);
        return true;
    };
    
    $("#download_press_kit form").submit(function(e) {
        e.preventDefault();
        var form = this;
        var form_values = {};
        $.each(form.elements, function(elem) {
            form_values[$(this).attr("name")] = $(this).attr("value");
        });
        if (!form_values['access_code']) {
            alert("Please enter a code");
            return false;
        }
        $.ajax({
            type: 'POST',
            url: downloadcontrol.request_download_url,
            data: {
                access_code: form_values['access_code']
            },
            dataType: 'json',
            success: ns.processDownloadRequest,
            error: function() {
                alert("D'oh! Unexpected error ocurred on the server.  Please try again");
            }
        });
        return true;
    });
});